package com.etrans.web.gps.base.controller;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import sun.misc.BASE64Encoder;

import com.etrans.web.gps.base.controller.BaseController;
import com.etrans.web.gps.common.http.HttpClient;
import com.etrans.web.gps.common.http.JSONUtil;
import com.etrans.web.gps.common.http.Response;
import com.etrans.web.gps.util.Config;

/**
 * 图片上传公共类
 * @author jw.chen
 *
 */

@Controller
@RequestMapping("/picture/")
@SuppressWarnings({"restriction","unchecked"})
public class PictureUpload extends BaseController {
	static final Logger log = LoggerFactory.getLogger(PictureUpload.class);
	
	@Autowired  
    private Config config; //引用统一的参数配置类 
	
	@RequestMapping(value = "uploadImg.html")
	public void uploadImg(HttpServletResponse response,MultipartHttpServletRequest multipartRequest, String fileUploadId) {
		log.info("开始上传图片");
		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		try {
			String realFileName = "";
			MultipartFile file = multipartRequest.getFile(fileUploadId); // 根据前台的name名称得到上传的文件
			if(file != null){
				realFileName = file.getOriginalFilename(); // 相同名字
			}
			if (file == null || file.getSize() == 0) {
				resultMap.put("error", "fileError");
				ajaxResultJson(response, resultMap);
				return;
			}
			String[] str = realFileName.split("\\.");
			if (str.length == 0) {
				resultMap.put("error", "fileError");
				ajaxResultJson(response, resultMap);
				return;
			}
			String suffix = str[str.length - 1].toString();
         
			// 校验后缀
			String[] suffixAry = { "jpg", "png", "gif", "jpeg" };
			List<String> tempList = Arrays.asList(suffixAry);
			if (!tempList.contains(suffix.toLowerCase())) {
				resultMap.put("error", "fileError");
				ajaxResultJson(response, resultMap);
				return;
			}  
			BASE64Encoder encoder = new BASE64Encoder();
			String imgBase64 = encoder.encode(file.getBytes());
			
			 SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
			 String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + suffix;
			
			 HashMap<String,Object> postData = new HashMap<String,Object>();
			 postData.put("filename", newFileName);
			 postData.put("filedata", imgBase64);
			 //post上传图片																			  
			 String fileurl=String.format("%s/open/fileserver/savefile.html", config.image_up_path);
			 Response res = HttpClient.post(fileurl, postData);
			 int status = res.getStatusCode();
			 if(status == 200){
				 String  imgPathJson = res.asString();
				 HashMap<String,Object> result = JSONUtil.fromJson(imgPathJson, HashMap.class);
				 resultMap.put("filename", result.get("data").toString());
			 }else{
				 resultMap.put("filename", "");
			 }
		} catch (Exception e) {
			e.printStackTrace();
			log.error("上传图片出错,原因是:"+e.toString());
			e.printStackTrace();
			resultMap.put("error", "exception");
		}
		ajaxResultJson(response, resultMap);
	}
}
